//
//  MessageCell.m
//  百车易车险
//
//  Created by chenxu on 14-8-29.
//  Copyright (c) 2014年 chenxu. All rights reserved.
//

#define kCellIdentifier_Message @"MessageCell"
#define kCellIdentifier_MessageMedia @"MessageMediaCell"
#define kCCellIdentifier_MessageMediaItem @"MessageMediaItemCCell"

#define kMessageCell_FontContent [UIFont systemFontOfSize:15]
#define kMessageCell_PadingWidth 20.0
#define kMessageCell_PadingHeight 11.0
#define kMessageCell_ContentWidth (kScreen_Width*0.6)
#define kMessageCell_TimeHeight 40.0
#define kMessageCell_UserIconWith 40.0


#import "MessageCell.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "UITapImageView.h"
#import "MessageMediaItemCCell.h"
#import "UICustomCollectionView.h"
#import "Login.h"
#import "NetAPIManager.h"

@interface MessageCell ()

@property (strong, nonatomic) UITapImageView *userIconView;
@property (strong, nonatomic) UITTTAttributedLabel *contentLabel;
@property (strong, nonatomic) UICustomCollectionView *mediaView;
@property (strong, nonatomic) NSMutableDictionary *imageViewsDict;

@property (strong, nonatomic) UIActivityIndicatorView *sendingStatus;
@property (strong, nonatomic) UITapImageView *failStatus;
@property (strong, nonatomic) UILabel *timeLabel;

@end

@implementation MessageCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor clearColor];
        
        if (!_userIconView) {
            _userIconView = [[UITapImageView alloc] initWithFrame:CGRectMake(0, 0, kMessageCell_UserIconWith, kMessageCell_UserIconWith)];
            [_userIconView doCircleFrame];
            [self.contentView addSubview:_userIconView];
        }
        
        if (!_bgImgView) {
            _bgImgView = [[UILongPressMenuImageView alloc] initWithFrame:CGRectZero];
            _bgImgView.userInteractionEnabled = YES;
            [self.contentView addSubview:_bgImgView];
        }
        
        if (!_contentLabel) {
            _contentLabel = [[UITTTAttributedLabel alloc] initWithFrame:CGRectMake(kMessageCell_PadingWidth, kMessageCell_PadingHeight, 0, 0)];
            _contentLabel.numberOfLines = 0;
            _contentLabel.font =kMessageCell_FontContent;
            _contentLabel.backgroundColor = [UIColor clearColor];
            [_bgImgView addSubview:_contentLabel];
        }
        if ([reuseIdentifier isEqualToString:kCellIdentifier_MessageMedia]) {
            if (!self.mediaView) {
                UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
                self.mediaView = [[UICustomCollectionView alloc] initWithFrame:CGRectMake(kMessageCell_PadingWidth, kMessageCell_PadingHeight, kMessageCell_ContentWidth, 80) collectionViewLayout:layout];
                self.mediaView.scrollEnabled = NO;
                [self.mediaView setBackgroundView:nil];
                [self.mediaView setBackgroundColor:[UIColor clearColor]];
                [self.mediaView registerClass:[MessageMediaItemCCell class] forCellWithReuseIdentifier:kCCellIdentifier_MessageMediaItem];
                self.mediaView.dataSource = self;
                self.mediaView.delegate = self;
                [_bgImgView addSubview:self.mediaView];
            }
            if (!_imageViewsDict) {
                _imageViewsDict = [[NSMutableDictionary alloc] init];
            }
        }
    }
    return self;
}


- (void)layoutSubviews{
    [super layoutSubviews];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (!_curPriMsg) {
        return;
    }
    CGFloat curBottomY = 0;
    NSString *displayStr = [MessageCell displayTimeStrWithCurMsg:_curPriMsg preMsg:_prePriMsg];
    if (displayStr) {
        if (!_timeLabel) {
            _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(kPaddingLeftWidth, (kMessageCell_TimeHeight- 20)/2, kScreen_Width-2*kPaddingLeftWidth, 20)];
            _timeLabel.backgroundColor = [UIColor clearColor];
            _timeLabel.font = [UIFont systemFontOfSize:12];
            _timeLabel.textColor = [UIColor colorWithHexString:@"0x999999"];
            _timeLabel.textAlignment = NSTextAlignmentCenter;
            [self.contentView addSubview:_timeLabel];
        }
        _timeLabel.hidden = NO;
        _timeLabel.text = displayStr;
        curBottomY += kMessageCell_TimeHeight;
    }else{
        _timeLabel.hidden = YES;
    }
    
    UIImage *bgImg;
    CGSize bgImgViewSize;
    CGSize textSize;
   // CGFloat mediaViewHeight = [MessageCell mediaViewHeightWithObj:_curPriMsg];
    
    if (_curPriMsg.Talk.length > 0) {
        textSize = [_curPriMsg.Talk getSizeWithFont:kMessageCell_FontContent constrainedToSize:CGSizeMake(kMessageCell_ContentWidth, CGFLOAT_MAX)];
    }else{
        textSize = CGSizeZero;
    }
    
    [_contentLabel setWidth:kMessageCell_ContentWidth];
    _contentLabel.text = _curPriMsg.Talk;
    [_contentLabel sizeToFit];
    textSize.height = CGRectGetHeight(_contentLabel.frame);
    
    
  
    [_contentLabel setY:kMessageCell_PadingHeight];
        
    bgImgViewSize = CGSizeMake(textSize.width +2*kMessageCell_PadingWidth, textSize.height +2*kMessageCell_PadingHeight);
    
    
    CGRect bgImgViewFrame;
    //
    if (_curPriMsg.sender == opposite) {
        //        这是好友发的
        bgImgViewFrame = CGRectMake(kPaddingLeftWidth +kMessageCell_UserIconWith, curBottomY +10, bgImgViewSize.width, bgImgViewSize.height);
        [_userIconView setCenter:CGPointMake(kPaddingLeftWidth +kMessageCell_UserIconWith/2, CGRectGetMaxY(bgImgViewFrame)- kMessageCell_UserIconWith/2)];
        bgImg = [[UIImage imageNamed:@"messageLeft_bg_img"] resizableImageWithCapInsets:UIEdgeInsetsMake(15, 25, 15, 25)];
        _contentLabel.textColor = [UIColor blackColor];
        _bgImgView.frame = bgImgViewFrame;
    }
    else
    {
        //        这是自己发的
        bgImgViewFrame = CGRectMake((kScreen_Width - kPaddingLeftWidth - kMessageCell_UserIconWith) -bgImgViewSize.width, curBottomY +10, bgImgViewSize.width, bgImgViewSize.height);
        [_userIconView setCenter:CGPointMake(kScreen_Width - kPaddingLeftWidth -kMessageCell_UserIconWith/2, CGRectGetMaxY(bgImgViewFrame)- kMessageCell_UserIconWith/2)];
        bgImg = [[UIImage imageNamed:@"messageRight_bg_img"] resizableImageWithCapInsets:UIEdgeInsetsMake(15, 25, 15, 25)];
        _contentLabel.textColor = [UIColor blackColor];
        _bgImgView.frame = bgImgViewFrame;
    }
    [_bgImgView setImage:bgImg];

    //用户端
    if (isUserClient) {
        //我的头像
        if (_curPriMsg.sender == me ) {
            [_userIconView sd_setImageWithURL:(NSURL*)[[Login curLoginUser] getIconUrl] placeholderImage:[UIImage imageNamed:@"avatar_girl"]];
        }
        //对面头像
        else{
            _userIconView.image = [UIImage imageNamed:@"avatar_girl"];
        }
    }
    //商家端
    else{
        //我的头像
        if (_curPriMsg.sender == opposite ) {
            NSString *url = [[NetAPIManager sharedManager]getAvatarUrl:_curPriMsg.username];
            [_userIconView sd_setImageWithURL:(NSURL*)url placeholderImage:[UIImage imageNamed:@"avatar_girl"]];
        }
        //对面头像
        else{
            _userIconView.image = [UIImage imageNamed:@"avatar_girl"];
        }
    }
 

    
    
   
    [self configSendStatus];
}

- (void)configSendStatus{
    CGPoint statusCenter = CGPointMake(CGRectGetMinX(_bgImgView.frame) -20, CGRectGetMinY(_bgImgView.frame)+ 15);
    if (_curPriMsg.sendStatus == PrivateMessageStatusSendSucess) {
        if (_sendingStatus) {
            [_sendingStatus stopAnimating];
        }
        if (_failStatus) {
            _failStatus.hidden = YES;
        }
    }else if (_curPriMsg.sendStatus == PrivateMessageStatusSending){
        if (!_sendingStatus) {
            _sendingStatus = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            _sendingStatus.hidesWhenStopped = YES;
            [self.contentView addSubview:_sendingStatus];
        }
        [_sendingStatus setCenter:statusCenter];
        [_sendingStatus startAnimating];
        if (_failStatus) {
            _failStatus.hidden = YES;
        }
    }else if (_curPriMsg.sendStatus == PrivateMessageStatusSendFail){
        if (_sendingStatus) {
            [_sendingStatus stopAnimating];
        }
        __weak typeof(self) weakSelf = self;
        if (!_failStatus) {
            _failStatus = [[UITapImageView alloc] initWithImage:[UIImage imageNamed:@"private_message_send_fail"]];
            if (weakSelf.resendMessageBlock) {
                [weakSelf.failStatus addTapBlock:^(id obj) {
                    weakSelf.resendMessageBlock(weakSelf.curPriMsg);
                }];
            }
            [self.contentView addSubview:_failStatus];
        }
        [_failStatus setCenter:statusCenter];
        _failStatus.hidden = NO;
    }
}


//设置cell 高度
+ (CGFloat)cellHeightWithObj:(id)obj preObj:(id)preObj{
    CGFloat cellHeight = 0;
    if ([obj isKindOfClass:[PrivateMessage class]]) {
        PrivateMessage *curPriMsg = (PrivateMessage *)obj;
        CGSize textSize = [curPriMsg.Talk getSizeWithFont:kMessageCell_FontContent constrainedToSize:CGSizeMake(kMessageCell_ContentWidth, CGFLOAT_MAX)];
        if ([curPriMsg.Talk containsEmoji]) {
            textSize.height += 10;
        }
        cellHeight += textSize.height + kMessageCell_PadingHeight*3;
        
        if ( curPriMsg.Talk && curPriMsg.Talk.length > 0) {
            cellHeight += kMessageCell_PadingHeight;
        }
        
        PrivateMessage *prePriMsg = (PrivateMessage *)preObj;
        NSString *displayStr = [MessageCell displayTimeStrWithCurMsg:curPriMsg preMsg:prePriMsg];
        if (displayStr) {
            cellHeight += kMessageCell_TimeHeight;
        }
    }
    return cellHeight;
}

+ (NSString *)displayTimeStrWithCurMsg:(PrivateMessage *)cur preMsg:(PrivateMessage *)pre{
    NSString *displayStr = nil;
    //超过一分钟的且没有对面的消息就显示时间
    if (!pre || [cur.created_at timeIntervalSinceDate:pre.created_at] > 1*60) {
        displayStr = [cur.created_at stringTimeDisplay];
    }
    return displayStr;
}



@end
